﻿using System;
using System.Collections.Generic;
using System.Text;
using Vara.Object;
using Vara.Asset;
using Vara.Utility;
using System.Data;

namespace Vara.Asset
{
    public class ExistingAssetController : AssetController
    {
        IAssetEvent_Actions AssetEventActions = new AssetEvent_Controller();

        private IVaraObject _ctx = null;
        public IVaraObject Context
        {
            get
            {
                return _ctx;
            }
            set
            {
                _ctx = value;
            }
        }

        public ExistingAssetController(IVaraObject objectContext)
        {
            this.Context = objectContext;
        }

        public override void InsertAsset(IAsset asset)
        {
            //if this is a new asset
            IAsset AssetToReturn; 
            int intNewID = 0;
            if (asset.ID == 0)
            {
                using (ISqlEngine Engine = VaraSqlEngineProvider.Get())
                {
                    List<ISqlEngineVariable> varsList = this.getAssetVariables(asset);

                    varsList.Add(VaraSqlEngineProvider.GetParam("@ObjectId", this.Context.ID));
                    ISqlEngineVariable[] var = varsList.ToArray();
                    intNewID = int.Parse(Engine.ExecuteProcedure("Insert_Asset", var).Rows[0]["ID"].ToString());
                }
                Refresh_Assets_List();
                AssetToReturn = this.ReturnAsset(intNewID);
                AssetEventActions.Insert(new AssetEvent("Created", ""), AssetToReturn);

            }
            //base.InsertAsset(asset);
        }


        protected virtual DataTable GetAssetsTable(int? objectId)
        {
            if (objectId.HasValue)
            {

                DataTable TableOfAssets = null;
                using (ISqlEngine Engine = VaraSqlEngineProvider.Get())
                {
                    TableOfAssets = Engine.ExecuteProcedure("Return_Assets", VaraSqlEngineProvider.GetParam("@objectId", objectId.Value));

                }

                return TableOfAssets;
            }
            else
            {
                return base.GetAssetsTable();
            }
        }
        protected override DataTable GetAssetsTable()
        {
            return this.GetAssetsTable(this.Context.ID);
        }
    }
}
